﻿// GameLogic.cpp
#include "GameLogic.h"

void GameLogic::updateGameState(int x, int y) {
    int gridX, gridY;
    convertToGridPosition(x, y, gridX, gridY);

    // 仅更新棋盘数据
    if (gameState.boardData[gridY][gridX] == '_') {
        char currentPiece = gameState.getCurrentPiece();
        gameState.boardData[gridY][gridX] = currentPiece;
        gameState.moveCount++;
    }
}

int GameLogic::checkGameOver(int x, int y) {
    int gridX, gridY;
    convertToGridPosition(x, y, gridX, gridY);
    char currentPiece = gameState.getCurrentPiece();

    // 先检查胜利
    if (checkWin(gridX, gridY, currentPiece)) {
        return 1; // 当前玩家胜利
    }

    // 检查平局
    if (checkDraw()) {
        return 2; // 平局
    }

    // 切换玩家
    gameState.currentPiece = (gameState.currentPiece + 1) % 2;

    return 0; // 游戏继续
}

void GameLogic::convertToGridPosition(int x, int y, int &gridX, int &gridY) const {
    gridX = x * 3 / gameState.Width;
    gridY = y * 3 / gameState.Height;
}

bool GameLogic::checkWin(int gridX, int gridY, char c) const {
    const auto& boardData = gameState.boardData;

    // 检查行
    if (boardData[gridY][0] == c && boardData[gridY][1] == c && boardData[gridY][2] == c) {
        return true;
    }

    // 检查列
    if (boardData[0][gridX] == c && boardData[1][gridX] == c && boardData[2][gridX] == c) {
        return true;
    }

    // 检查主对角线
    if (gridX == gridY && boardData[0][0] == c && boardData[1][1] == c && boardData[2][2] == c) {
        return true;
    }

    // 检查副对角线
    if (gridX + gridY == 2 && boardData[0][2] == c && boardData[1][1] == c && boardData[2][0] == c) {
        return true;
    }

    return false;
}

bool GameLogic::checkDraw() const {
    return gameState.moveCount >= 9;
}
